#!/usr/bin/python3
import os
from .Entity import Entity
from .Biz_Method import Biz_Method
from utils import My_Util2


class Service(Biz_Method):
    """
    业务接口
    """

    def __init__(self, context, entity: Entity) -> None:
        self.context = context
        self.entity: Entity = entity
        self.prefix: str = self.entity.table_name.split("_")[0].lower()
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_includes(self):
        package = self.entity.package
        prefix = self.entity.table_name.split("_")[0].lower()
        entity_name = self.entity.name
        includes = list()

        includes.append(
            f"""import com.baomidou.mybatisplus.extension.plugins.pagination.Page;"""
        )
        includes.append(
            f"""import com.baomidou.mybatisplus.extension.service.IService;"""
        )
        includes.append(f"""import {package}.internal.lookup.ILookupConstants;""")
        includes.append(f"""import {package}.internal.entity.{entity_name};""")
        includes.append(f"""import {package}.internal.lambdas.Fn;""")
        includes.append(f"""import {package}.internal.transaction.BusinessException;""")
        includes.append(f"""import {package}.{prefix}.bo.{entity_name}BO;""")
        for field in self.entity.fields:
            if field.ignore():
                continue
            if field.is_sort():
                includes.append(f"""import {package}.internal.model.SwapBO;""")
        includes.append(
            f"""import {package}.{prefix}.query.exists.{entity_name}Exists;"""
        )
        includes.append(f"""import {package}.{prefix}.bo.{entity_name}UpdateBO;""")
        includes.append(f"""import {package}.{prefix}.query.{entity_name}QueryInfo;""")
        includes.append(f"""import {package}.{prefix}.vo.{entity_name}VO;""")
        includes.append(f"""import java.util.List;""")
        includes = self.my_util2.sort_import_order(includes)
        return "\r".join(includes)

    def code_save(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 新增{comment}记录
     *
     * @param {object_name}BO {comment}新增对象
     * @return 新增结果
     */
    boolean save({entity_name}BO {object_name}BO) throws BusinessException;"""

    def code_remove_list(self):
        entity_name = self.entity.name
        comment = self.entity.comment
        return f"""
    /**
     * 删除{comment}记录
     *
     * @param ids {comment}主键，多个之间用逗号分隔
     * @return 删除结果
     */
    boolean remove{entity_name}ByIds(String ids) throws BusinessException;"""

    def code_update(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 更新{comment}记录
     *
     * @param {object_name}UpdateBO {comment}更新对象
     * @return 结果
     */
    boolean update{entity_name}ById({entity_name}UpdateBO {object_name}UpdateBO) throws BusinessException;"""

    def code_nullify_or_revert(self):
        if not self.entity.has_status():
            return None
        comment = self.entity.comment
        return f"""
    /**
     * 作废或还原{comment}记录
     *
     * @param ids {comment}主键，多个之间用逗号分隔
     * @return 结果
     */
    boolean nullifyOrRevertByIds(String ids) throws BusinessException;"""

    def code_swap(self):
        if not self.entity.has_sort():
            return None
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 交换{comment}记录顺序
     *
     * @param SwapBO 交换对象
     * @return 结果
     */
    boolean swap{entity_name}(SwapBO swapBO) throws BusinessException;"""

    def code_get(self):
        entity_name = self.entity.name
        comment = self.entity.comment
        return f"""
    /**
     * 按主键获取{comment}视图对象
     *
     * @param id {comment}主键
     * @return {comment}视图对象
     */
    {entity_name}VO getById(Long id);"""

    def code_get_by_condition(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 根据条件查找{comment}视图对象
     *
     * @param {object_name}Exists 条件
     * @return {comment}视图对象
     */
    {entity_name}VO getByCondition({entity_name}Exists {object_name}Exists);"""

    def code_get_by_condition_columns(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 根据条件查找{comment}视图对象
     *
     * @param {object_name}Exists 条件
     * @columns 指定列
     * @return {comment}视图对象
     */
    {entity_name}VO getByCondition({entity_name}Exists {object_name}Exists, List<Fn<{entity_name}>> columns);"""

    def code_page(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 分页查询{comment}
     *
     * @param {object_name}QueryInfo {comment}分页查询参数对象
     * @param p 分页对象
     * @return {comment}分页结果
     */
    Page<{entity_name}VO> getPageByQueryInfo({entity_name}QueryInfo {object_name}QueryInfo, Page<{entity_name}> p);"""

    def code_list(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 按条件查询{comment}列表
     *
     * @param {object_name}Exists 条件
     * @return 结果
     */
    List<{entity_name}VO> list({entity_name}Exists {object_name}Exists);"""

    def code_list_columns(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 按条件查询{comment}列表
     *
     * @param {object_name}Exists 条件
     * @param columns 指定列
     * @return 结果
     */
    List<{entity_name}VO> list({entity_name}Exists {object_name}Exists, List<Fn<{entity_name}>> columns);"""

    def code_next_sort(self):
        if not self.entity.has_sort():
            return None
        return f"""
    /**
     * 获取下一个排序号
     *
     * @return 下一个排序号
     */
    Integer getNextSortNumber();"""

    def code_exists(self):
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment
        return f"""
    /**
     * 判断{comment}记录是否存在
     *
     * @param {object_name}Exists 判断条件
     * @return 结果
     */
    boolean exists({entity_name}Exists {object_name}Exists);"""

    def code(self):
        """
        获取Service代码
        """
        author = self.entity.author
        package = self.entity.package
        prefix = self.prefix
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment

        includes = self.code_includes()

        codes = list()
        save = self.code_save()
        codes.append(save)
        remove_list = self.code_remove_list()
        codes.append(remove_list)
        update = self.code_update()
        codes.append(update)
        nullify_or_revert = self.code_nullify_or_revert()
        if nullify_or_revert is not None:
            codes.append(nullify_or_revert)
        swap = self.code_swap()
        if swap is not None:
            codes.append(swap)
        get = self.code_get()
        codes.append(get)
        # get_by_condition = self.code_get_by_condition()
        # codes.append(get_by_condition)
        page = self.code_page()
        codes.append(page)
        code_list = self.code_list()
        codes.append(code_list)
        next_sort = self.code_next_sort()
        if next_sort is not None:
            codes.append(next_sort)
        exists = self.code_exists()
        codes.append(exists)
        codes = "\r".join(codes)

        return f"""package {package}.{prefix}.service;

{includes}

/**
 * <p>
 * {comment}业务接口
 * </p>
 *
 * @author {author}
 */
public interface I{entity_name}Service extends IService<{entity_name}>, ILookupConstants {"{"}
{codes}
{"}"}
"""

    def save_file(self, dir):
        _target_dir = os.path.join(dir, self.prefix, "service")
        if not os.path.exists(_target_dir):
            os.mkdir(_target_dir)
        with open(
            os.path.join(_target_dir, "I{}Service.java".format(self.entity.name)),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())
